/*
Libreria ADC ADS1247
ADC 24 bit 8ch single / 4ch Differential
HW TEST 4
Manuel Baldo

Ref interna 2,048V

*/


#define delay_read  10 // tempo in us di attesa risposta ADC attesa risposta 50 TOSC

#define DOUT_adc	PORTGbits.RG7       				 
#define DRDY_adc	PORTCbits.RC14 //PORTBbits.RB12
#define DIN_adc		LATGbits.LATG8
#define SCLK_adc	LATGbits.LATG6
#define CS_adc		LATBbits.LATB13		 
#define START_pin	LATCbits.LATC13  // min 3 tosc
#define RESET_pin	// LATCbits.LATC14  // min 4 tosc, 0,6ms to SCLK
#define OSC_adc		4096000  // Frequenza oscillatore interno

#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))


//ADRRESS
#define MUX0	0	// Enable Burnout Currento, set IN+ e IN- 
#define VBIAS	1	// Enable bias Voltage in the INPUT 0 e 1
#define MUX1	2	// Vref,MUXCal
#define SYS0	3	// PGA e datarate OUT 20 a 2KSPS
#define OFC0	4	// 
#define OFC1	5
#define OFC2	6
#define FSC0	7
#define FSC1	8
#define FSC2	9
#define IDAC0	10	// Set DRDY Mode,Corrente IDAC
#define IDAC1	11	// Pin di Output IDAC1 e IDAC2
#define GPIOCFG	12
#define GPIODIR	13
#define GPIODAT 14

//COMMANDS
#define WAKEUP	0b00000000	// Exit sleep mode
#define SLEEP	0b00000010	// Enter sleep mode
#define SYNC	0b00000100	// Sincronizza la conversione AD
#define RESET	0b00000110
#define NOP		0b11111111
#define RDATA	0b00010010
#define RDATAC	0b00010100
#define SDATAC	0b00010110
#define RREG	0b00100000  // 0010 rrrr Indirizzo REG
#define WREG	0b01000000  // 0100 rrrr Indirizzo REG
#define SYSOCAL 0b01100000	// System offset calibration
#define SYSGCAL 0b01100001	// System gain calibration
#define SELFOCAL 0b0110010 	// Self offset calibration


void Init_ADS1247(void);
void Setup_ADS1247(void);
void Delay_SCK(void);
void Delay_ns(long ns);
void Write_Byte(unsigned char byte);
unsigned long Read_bits(unsigned char bits);
unsigned long Read_FSC(void);
unsigned long Read_OFS(void);
long ADS1247_OUT(unsigned char time_out);
void PGA_SPS_ADS1247(unsigned char pga,unsigned int sps);
unsigned char Read_REG(unsigned char addr);
void OfsCal_ADS1247(void);
void Sync_ADC(void);